var jq13 = jQuery.noConflict(true);

jq13("#twitter-ui").ready(function() {		
	TwitterUI.start();
});

var Utiles={
	disable:function(el){
		el.attr("disabled",true);
		el.addClass("ui-state-disabled");
	},
	enable:function(el){
		el.attr("disabled",false);
		el.removeClass("ui-state-disabled");
	},
	createButton:function($button){		
		$button.hover(
			function(){ 
				jq13(this).addClass("ui-state-hover"); 
			},
			function(){ 
				jq13(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			jq13(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
			jq13(this).removeClass("ui-state-active");
		});		
	}
	

};
var TwitterUI ={
	$tabHome:{},
	twitterStatus:{},
	twitterUser:{},
	selectedTab:"",
	statusItem:'<li id="status_@id" class="hentry status"><span class="thumb vcard author"> <a class="url" href="http://twitter.com/@user_screen_name"><img height="48" width="48" src="@user_profile_image_url" class="photo fn" alt="@user_name" /></a></span><span class="status-body"><span class="entry-content">@status_entry-content<span class="published">@created_at</span> by <strong><a title="@user_name" class="screen-name" href="http://twitter.com/@user_screen_name">@user_screen_name</a></strong></span></span><br/><div class="clear"></div></li>',
	redOnly:true,
	resetAllForms:function(){
		jq13("#twitter-ui :input").val("");
	},
	start:function(){
		TwitterUI.resetAllForms();
		TwitterService.userExists(function(exists){			
			if(exists){
				jq13("#twitter-client").show();
				TwitterUI.init();
				return;
			}
			jq13("#twitter-client").hide();
			var $twitterAouth=jq13("#twitter-aouth");
			$twitterAouth.show();
			
			var $signIn=jq13($twitterAouth.find("div").get(0)).css("display","block");
			$signIn.hover(	function(){jq13(this).addClass("twitter-sign-in-over").removeClass("twitter-sign-in");},
							function(){jq13(this).addClass("twitter-sign-in").removeClass("twitter-sign-in-over");});
			var $complete=jq13($twitterAouth.find("form").get(0));
			$complete.hide();
			var $pin=$complete.find("input");			
			$complete.find("button").click(function(event){			
				TwitterService.storeTokenWithSecret($pin.val(),function(){
					$twitterAouth.hide();
					jq13("#twitter-client").show();
					TwitterUI.init();
				});
				return false;
			});
			$signIn.click(function(event){
				TwitterService.getAuthUrl(function(url){
					$signIn.hide();
					$complete.show();
					var twitterOAuth = window.open(url,'twitterOAuth','width=1000,height=400,toolbar=0,resizable=0');
									
				});
			});
		});
		
	},
	init:function(){				 
	  this.enhanceButtons();	
	  var that=this;	  	  
	  this.redOnly=jq13("#twitter-status").length==0;
	  that.createHeadBar();
	  that.createMenuBar();
	  TwitterService.getMyProfileInfo(function(twitterUser){
		  that.twitterUser=twitterUser;

		  that.createProfileBar(twitterUser);
		  if(!that.redOnly){
			  that.createTinyUrlArea();
			  that.createNewStatusArea();
		  }	
	  });	  
	  jq13("#more-statuses").click(function(){
		  that.onTabSelected(that.selectedTab, true);
	  });
	},
	createHeadBar:function(){		
		var $headBar=jq13('#twitter-head-bar > li').addClass('horizontal');		
		$headBar.filter(".refresh-button").click(function(){
			TwitterUI.init();
		});
		var $poweredBy=$headBar.eq(2);
		TwitterUI.asignAboutPopup($poweredBy);		
		var $logout=$headBar.eq(3);
		$logout.click(function(){			
			TwitterService.logout(function(){
				//alert("logout");
				TwitterUI.start();
			});
		});
	},
	enhanceButtons:function(){
		jq13(".ui-button").each(function(){
			Utiles.createButton(jq13(this));
		});
	},
	createProfileBar:function(twitterUser){		
		$li=jq13('#twitter-profile-bar > li.profile').addClass('horizontal');					
		var $profileImage=jq13('<img height="48" width="48" src="" class="photo fn" alt="" />')
			.attr('src', twitterUser.profile_image_url)
			.attr('alt', twitterUser.name)
			.prependTo($li.filter(".me")
			.html(twitterUser.screen_name)
			.attr("title",twitterUser.name));
			
		$li.filter(".following")
			.html("following ("+ twitterUser.friends_count+")");
		$li.filter(".followers")
			.html("followers ("+ twitterUser.followers_count+")");		
	},
	createMenuBar:function(){
		
		this.tabsDataMethodsCalls={'tabs-home':{method:TwitterService.getFriendsTimeLine,
												page:0,
												renderer:TwitterUI.renderStatuses},
								   'tabs-my':{	method:TwitterService.getUserTimeLine,
												page:0,
												renderer:TwitterUI.renderStatuses},
					 				'tabs-replies':{method:TwitterService.getReplies,
													page:0,
													renderer:TwitterUI.renderStatuses},
					 				'tabs-direct':{method:TwitterService.getDirect,
												   page:0,
												   renderer:TwitterUI.renderDirectMessages},
														
					 				'tabs-favorite':{method:TwitterService.getFavorites,
													 page:0,
													 renderer:TwitterUI.renderStatuses},
					 				'tabs-everyone':{method:TwitterService.getEveryOne,
													page:0,
													renderer:TwitterUI.renderStatuses}
								 };
		
				
		var that=this;
		this.$tabs=jq13("#tabs");
		this.$tabs.bind('tabsshow', function(event, ui) {			
			that.selectedTab=ui.panel.id;
		    that.onTabSelected(ui.panel.id );
		});
		this.$tabs.tabs({ cache: false });
		this.$tabs.tabs( 'show' , 'tabs-home');
		
		
	},
	createTinyUrlArea:function(){
		jq13(".make-tiny").click(function(event){			
			var $normalUrl=jq13(".normal-url");
			if($normalUrl.val().length==0)				
				return false;						
			TinyUrlService.makeTiny($normalUrl.val(),function(tinyUrl){			
				if(tinyUrl==null)
					return;								
				jq13("#tiny-url-form >label").html(tinyUrl);			
			});
			return false;
		});
	},
	createNewStatusArea:function(){		
		if(jq13("#twitter-status").length==0)
			return;
		var that=this;
		var $counter=jq13('#twitter-status-menu-bar .counter');
		this.$clearButton=jq13('#twitter-status-menu-bar .clear-button');
		var $submitButton=jq13('#create-status');
		this.$statusTextarea=jq13('#twitter-status .status-textarea');			
		this.$clearButton.click(function (event){
			that.$statusTextarea.val("");
			that.twitterStatus={};
			that.$statusTextarea.trigger("keypress");
			
		});
		this.$statusTextarea.keypress(function(event){			
			updateCounter();
		});		
		var calculateCounter=function(){
			return 140-that.$statusTextarea.val().length;
		};
		var updateCounter=function(){
			var count=calculateCounter();
			if(count<0)
				$counter.css("background","gray");
			else
				$counter.css("background","pink");
			$counter.text(count);
		};
		$submitButton.click(function(){
			if(that.$statusTextarea.val().length==0)
				return false;			
			Utiles.disable($submitButton);
			TwitterService.updateStatus({status:that.$statusTextarea.val(),replayTo:that.twitterStatus.id},function(result){
				Utiles.enable($submitButton);	
				that.selectedTab='tabs-home';
			    that.onTabSelected('tabs-home');
				that.$clearButton.trigger('click');
				return false;
			});
			return false;
		});		
		
	},
	onTabSelected:function(panelId,more){

		var that=this;
		var currTabController=this.tabsDataMethodsCalls[panelId];
		$tab=jq13('#'+panelId);
		var appendTo=$tab;		
		if(more){
			var $lastStatus=$tab.find("li:last");			
			currTabController.method(++currTabController.page,function(twitterStatuses){
				if(twitterStatuses.length===0){				
					return;	
				}				
				currTabController.renderer(twitterStatuses).insertAfter($lastStatus);	
				}
			);
			return;
		}
		$tab.html("loading ...");
		currTabController.page=0;
		currTabController.method(++currTabController.page,function(twitterStatuses){
				if(twitterStatuses.length===0){
					$tab.html("There is no data");
					return;	
				}
				$tab.empty();
				currTabController.renderer(twitterStatuses).appendTo($tab);	
			}
		);
	},
	renderDirectMessages:function(twitterDirectMessages){
		var menu='<div class="actions" ><a title="delete this message" id="delete_message_@id" >del</a><a title="reply to @user_screen_name" class="reply">reply</a></div>';
		var $html=TwitterUI.render(twitterDirectMessages,TwitterUI.directMessageUtilityMenu,jq13(TwitterUI.statusItem).append(menu).parent().html());
		var $topMenu=jq13('<div id="directMessagesMenu" class="actions" ><a title="delete all messages" >delete all</a></div>');
		
		var $deleteAll=$topMenu.css("visibility","visible").find("a");
		$deleteAll.click(function(event){			
			Utiles.disable($deleteAll);
			var ids=[];
			$html.find("li").each(function(){
				var id=jq13(this).attr("id").replace(/status_/,"");
				ids.push(id);
			});
			TwitterService.removeDirectMessages(ids,function(isOk){
				Utiles.enable($deleteAll);
				if(isOk){
					TwitterUI.selectedTab='tabs-direct';
					TwitterUI.onTabSelected('tabs-direct');
				}
			});
		});
		return $html.prepend($topMenu); 
	},
	renderStatuses:function(twitterStatuses){
		var menu='<div class="actions" ><a title="favorite this update" id="status_star_@id" class="fav-action">aa</a><a title="reply to @user_screen_name" class="reply">reply</a><a title="retwitte" class="retwitte">rt</a></div>';
		var $html=TwitterUI.render(twitterStatuses,TwitterUI.statusUtilityMenu,jq13(TwitterUI.statusItem).append(menu).parent().html());
		return $html; 
	},
	render:function(twitterStatuses,createUtilityMenu,statusItem){
		var $html=jq13('<ol class="statuses-list" ></ol>');
		var that=this;						
		jq13.each(twitterStatuses,function(){
			var li=statusItem
						.replace(/@id/g, this.id)
						.replace(/@user_screen_name/g, this.user.screen_name)
						.replace(/@user_profile_image_url/g, this.user.profile_image_url)
						.replace(/@user_name/g, this.user.name)
						.replace(/@created_at/g,this.created_at)
						.replace(/@status_entry-content/g,this.renderedText);
			var $li=jq13(li);			
			//$li.find(".published").prettyDate(this.created_at);			
			that.asignProfileDataPopup($li.find(".author"),this.user,"popup-"+this.id);			
			var $actions=$li.find(".actions");
			if(!that.redOnly)
				createUtilityMenu($li,this);
			else
				$actions.empty();
			$li.mouseover(function(event){				
				$li.addClass("status-selected");
				$actions.css("visibility","visible");
			}).mouseout(function(event){
				$li.removeClass("status-selected");
				$actions.css("visibility","hidden");
			}).appendTo($html);
			
		});				
		
		return $html;					
	},
	asignProfileDataPopup:function($author,user,id){		
		var $popup=jq13("#profile-data").clone().attr("id",id).appendTo(jq13("#twitter-client"));
		var t;
		var t2;
		$author.hover(function(event){
			t2=setTimeout(function(){
				clearTimeout(t); 
				var pos = $author.position();
				$popup.css('position', 'absolute').css( {top:pos.top+70,left:pos.left});			
				//$popup.css("top","-"+event.clientY+"px").show();			
				$popup.find("#profile-image").attr("src",user.profile_image_url);
				$popup.find("li.name >strong").text(user.name+" ( "+user.screen_name+" )");
				$popup.find("li.location >strong").text(user.location);
				$popup.find("li.web > a").attr("href",user.url).text(user.url);
				$popup.find("li.following > a").attr("href","").text("Following - "+user.friends_count);
				$popup.find("li.followers > a").attr("href","").text("Followers - "+user.followers_count);
				$popup.find("p.bio").text(user.description);
	  			$popup.show();
			},1500);
		},
  	    function(){
			clearTimeout(t2);
			t = setTimeout(function(){
				$popup.hide();										
			},1000);
  	    });
		
		$popup.hover(function(event){
			clearTimeout(t);
		},function(event){					
			t = setTimeout(function(){
					$popup.hide();},1000);
		});
		
	},
	asignAboutPopup:function($el){
		var $popup=jq13("#powered-by");
		$el.click(function(){
			var pos = $el.position();
			$popup.css('position', 'absolute').css( {top:pos.top+20,left:pos.left-80});
			$popup.show();
		});
		
		$popup.find("a:eq(0)").click(function(){			
			$popup.hide();
		});
	},
	directMessageUtilityMenu:function($li,directMessage){
		var $delete=$li.find("a[id^=delete_message_]");
		$delete.click(function(){			
			TwitterService.removeDirectMessages([directMessage.id],function(isOk){});
		});
		var $replay=$li.find(".replay");
		$replay.click(function(){alert('not implemented');});
		
	},
	statusUtilityMenu:function($li,twitterStatus){				
		var $favAction=$li.find("a.fav-action");			
		if(twitterStatus.favorited)
			$favAction.addClass("fav").html('unfavorite');
		else
			$favAction.addClass("non-fav").html('favorite');
		// favorite / unfavorite click event 
		$favAction.click(function(event){			
			if($favAction.hasClass("non-fav")){						
				TwitterService.addToFavorites(twitterStatus.id,function(isOk){							
					$favAction.removeClass("non-fav").addClass("fav").html("unfavorite");	
					$favAction.attr("title","unfavorite this update");							
				});
				return;
			}
			TwitterService.removeFromFavorites(twitterStatus.id,function(isOk){							
				$favAction.removeClass("fav").addClass("non-fav").html("favorite");
				$favAction.attr("title","favorite this update");				
			});
		});
		
		// reply click event
		$reply=$li.find("a.reply");		
		$reply.click(function(event){			
			TwitterUI.writeIntoTextArea("@"+twitterStatus.user.screen_name);
			TwitterUI.twitterStatus=twitterStatus;
		});
		$retwitte=$li.find("a.retwitte");
		$retwitte.click(function(event){			
			TwitterUI.writeIntoTextArea("RT @"+twitterStatus.user.screen_name+" "+twitterStatus.text);
			TwitterUI.twitterStatus=twitterStatus;
		});
		
		if(TwitterUI.twitterUser.id===twitterStatus.user.id){
			$delete=jq13('<a title="delete status" class="delete">del</a>');
			$delete.click(function(){
				TwitterService.deleteStatus(twitterStatus.id,function(delited){$li.remove();});
			}).insertAfter($retwitte);
		}
		
	},
	writeIntoTextArea:function(txt){				
		this.$clearButton.trigger("click");
		this.$statusTextarea.val(txt);
		this.$statusTextarea.trigger("keypress");				
	}
};
